﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using WMM.Tapioca.Linkbase;
using WMM.Tapioca.Instance;
using WMM.Tapioca.Taxonomy;

namespace WMM.Tapioca.Formula.Filters
{
    /// <summary>
    /// The parent filter can be used to select facts that have a specified parent element. 
    /// </summary>
    public class ParentFilter : Filter
    {
        private string parent;

        /// <returns> XPath expression contained by the tf:qnameExpression element.  </returns>
        public string Parent
        {
            get { return parent; }
            set { parent = value; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public ParentFilter(Resource resource)
            : base(resource)
        {
            XElement parentX = resource.ResourceXElement.Descendants().Where(d => d.Parent.Name.LocalName.Equals("parent") && 
            d.Name.LocalName.Equals("qname")).FirstOrDefault();

            if (parentX != null)
            {
                string qname =  parentX.Value;
                qname = qname.TrimEnd().TrimStart();
                qname = Regex.Replace(qname, @"\s+", " ");
                parent = qname;
            }

            XElement qnameExpressionX = resource.ResourceXElement.Descendants().Where(d => d.Parent.Name.LocalName.Equals("parent") &&
            d.Name.LocalName.Equals("qnameExpression")).FirstOrDefault();

            if (qnameExpressionX != null)
            {
                string expression = qnameExpressionX.Value;
                expression = expression.TrimEnd().TrimStart();
                expression = Regex.Replace(expression, @"\s+", " ");
                parent = EvaluateExpression(expression);
            }
        }


        public override List<FactItem> EvaluateFilter(VariableSet variableSet, List<FactItem> itemsToFilter, DTS dts)
        {
            this.dts = dts;

            List<FactItem> itemListTemp = new List<FactItem>();

            foreach (FactItem item in itemsToFilter)
            {
                string parent = Parent.Substring(Parent.IndexOf(':') + 1);

                if (Complement ? !item.FactElement.Parent.Name.LocalName.Equals(parent) : item.FactElement.Parent.Name.LocalName.Equals(parent))
                {
                    itemListTemp.Add(item);
                }
            }

            return itemListTemp;
        }
    }
}
